package 其他;

import 剑指offer.TreeNode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class 二叉树的公共祖先 {
    Map<TreeNode,TreeNode> parent = new HashMap<>();
    Set<Integer> visited = new HashSet<>();
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while (p != null){
            visited.add(p.val);
            p = parent.get(p);
        }
        while (q != null){
            if(visited.contains(q.val)){
                return q;
            }
            q = parent.get(q);
        }
        return null;
    }
    public void dfs(TreeNode root){
        if(root.left != null){
            parent.put(root.left,root);
            dfs(root.left);
        }
        if(root.right != null){
            parent.put(root.right,root);
            dfs(root.right);
        }
    }
}
